package parser

import (
	"fmt"
	"github.com/fatih/color"
	"github.com/hashicorp/go-version"
	"github.com/hashicorp/hcl/v2"
	"github.com/ihaiker/tfwrapper/internal/errors"
	"github.com/ihaiker/tfwrapper/internal/shells"
	"github.com/ihaiker/tfwrapper/internal/util"
	"github.com/sirupsen/logrus"
	"regexp"
)

var terraformVersionRegex = regexp.MustCompile(`Terraform (v?\d+\.\d+\.\d+).*`)

func getTerraformVersion(binary *string) (string, hcl.Diagnostics) {
	if binary == nil {
		binary = util.StringPtr("terraform")
	}

	stdout, stderr, err := shells.Terraform(*binary, "--version").RunWithOutput()
	if err != nil {
		return "", errors.Diagnostics(err.Error(), fmt.Errorf(stderr))
	}

	matches := terraformVersionRegex.FindStringSubmatch(stdout)
	if len(matches) != 2 {
		return "", errors.NewDiagnostics("Get terraform version",
			"Unable to parse terraform version output: %s", stdout)
	}
	terraformVersion := matches[1]
	logrus.Infof("terraform version: %s", color.HiGreenString(terraformVersion))
	return terraformVersion, nil
}

func checkVersionMeetsConstraint(app string, current string, constraint *string) error {
	if constraint == nil {
		return nil
	}
	currentVersion, err := version.NewVersion(current)
	if err != nil {
		return err
	}

	versionConstraint, err := version.NewConstraint(*constraint)
	if err != nil {
		return err
	}

	if !versionConstraint.Check(currentVersion) {
		return fmt.Errorf("the currently installed version of %s (%s) is not compatible with the version constraint requiring (%s)",
			app, currentVersion.String(), versionConstraint.String())
	}
	return nil
}
